<template>
	<el-card>
		<div class="mb20">
			<div class="avatar-box">
				<div v-if="store.userStore.user.avatar" class="mb10">
					<el-image
						style="width: 100px; height: 100px"
						:src="store.userStore.user.avatar"
						:preview-teleported="true"
						:zoom-rate="1.0"
						:preview-src-list="[store.userStore.user.avatar]"
						:initial-index="0"
						fit="cover"
					/>
				</div>
				<img v-else src="@/assets/default.png" />
				<span class="change" @click.stop="startUpImg" v-if="hasRule('Me/ModifyAvatar')">{{ $t('edit') }}</span>
			</div>
		</div>
		<div class="mb20">{{ $t('settings.BaseInfo') }}</div>
		<div class="mb20">{{ $t('settings.DepartmentInfo') }}：{{ store.userStore.user.departmentName }}</div>
		<div class="mb20 flex flexL">
			<span class="mr30">{{ $t('settings.UserName') }}：{{ store.userStore.user.username }}</span>
			<el-button type="primary" link @click="editName" v-if="hasRule('Me/ModifyName')">{{ $t('edit') }}</el-button>
		</div>
		<div class="mb20">
			<el-button type="default" @click="logout" :loading="loginouting">{{ $t('app.signOut') }}</el-button>
			<el-button type="default" @click="change" v-if="hasRule('Me/ChangePassword')">{{ $t('router.profilePassword') }}</el-button>
		</div>
		<el-dialog v-model="visibleName" :title="$t('edit')" :close-on-click-modal="false" width="500px" center :destroy-on-close="true">
			<!-- @keyup.enter="handleDataForm()" -->
			<el-form ref="dataFormNameRef" :model="dataFormName" :rules="dataRulesName" label-width="100px">
				<el-form-item prop="name" :label="$t('profile.username')">
					<el-input v-model="dataFormName.name" maxlength="50" show-word-limit clearable style="width:250px;"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleDataFormName" :loading="btnloading">{{ $t('confirm') }}</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		<el-dialog v-model="visible" :title="$t('router.profilePassword')" :close-on-click-modal="false" width="600px" center :destroy-on-close="true">
			<!-- @keyup.enter="handleDataForm()" -->
			<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="200px">
				<el-form-item :label="$t('profile.username')">
					<span>{{ store.userStore.user.username }}</span>
				</el-form-item>
				<el-form-item prop="password" :label="$t('profile.oldPassword')">
					<el-input v-model="dataForm.password" type="password" style="width:250px;"></el-input>
				</el-form-item>
				<el-form-item prop="newPassword" :label="$t('profile.newPassword')">
					<el-input v-model="dataForm.newPassword" type="password" style="width:250px;"></el-input>
				</el-form-item>
				<el-form-item prop="confirmPassword" :label="$t('profile.confirmPassword')">
					<el-input v-model="dataForm.confirmPassword" type="password" style="width:250px;"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleDataForm" :loading="btnloading">{{ $t('confirm') }}</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
		<imgCropper ref="imgCropperRef" :title="$t('edit')" @upload="uploadSuccess" />
	</el-card>
</template>

<script setup lang="ts" name="ProfilePassword">
import { ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import store from '@/store'
import { validatePassword } from '@/utils/validate'
import { updatePasswordApi, updateUsernameApi } from '@/api/user'
import { ElMessage } from 'element-plus'
import { closeTab } from '@/utils/tabs'
import { Storage } from '@/utils/storage'
import { decrypt, hasRule } from '@/utils/tool'
import imgCropper from '@/components/AvatarCropper/cropper.vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()

const router = useRouter()
const route = useRoute()
const visibleName = ref(false)
const visible = ref(false)
const btnloading = ref(false)
const loginouting = ref(false)
const dataFormNameRef: any = ref(null)
const dataFormRef: any = ref(null)
const imgCropperRef = ref()

const logout = () => {
	loginouting.value = true
	store.userStore.logoutAction().then(() => {
		loginouting.value = false
		// 刷新页面
		location.reload()
	}).catch(() => {
		loginouting.value = false
	})
}
// 修改头像
const startUpImg = () => {
	imgCropperRef.value.openDialog(store.userStore.user.avatar)
}
// 上传并裁剪完成
const uploadSuccess = (img: any) => {
	// 修改头像
	updateUsernameApi({
		id: store.userStore.user.id,
		avatar: img
	}).then(async () => {
		let login_data = Storage.getItem('login_info')
		login_data.user_info.user.avatar = img
		Storage.setItem('login_info', login_data)
		await store.userStore.getUserInfoAction()
		ElMessage.success(t('successMsg'))
	}).catch(() => {
		ElMessage.error(t('errorMsg'))
	})
}
const editName = () => {
	btnloading.value = false
	dataFormName.value.name = store.userStore.user.username
	visibleName.value = true
}

const change = () => {
	btnloading.value = false
	visible.value = true
}
const dataFormName: any = ref({
	name: '',
})
const dataForm: any = ref({
	// password: '',
	newPassword: '',
	confirmPassword: ''
})

const validatePass = (rule: any, value: any, callback: any) => {
	if (value === '') {
		callback(new Error(t('profile.enterNewPassword')))
	} else if (value.length < 6) {
		callback(new Error(t('profile.minDigits')))
	} else {
		if (dataForm.value.confirmPassword !== '') {
			if (!dataForm.value) return
			dataFormRef.value.validateField('confirmPassword', () => null)
		}
		callback()
	}
}
const validatePass2 = (rule: any, value: any, callback: any) => {
	if (value === '') {
		callback(new Error(t('profile.enterNewPasswordAgain')))
	} else if (value.length < 6) {
		callback(new Error(t('profile.minDigits')))
	}  else if (value !== dataForm.value.newPassword) {
		callback(new Error(t('profile.inconsistent')))
	} else {
		callback()
	}
}
const dataRulesName = ref({
	name: [{ required: true, message: t('required'), trigger: 'blur' }],
})
const dataRules = ref({
	password: [{ required: true, message: t('required'), trigger: 'blur' }],
	newPassword: [{ required: true, validator: validatePass, trigger: 'blur' }],
	confirmPassword: [{ required: true, validator: validatePass2, trigger: 'blur' }]
})

const handleDataForm = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		// 修改密码
		if(Storage.getItem('username_key')){
			btnloading.value = true
			updatePasswordApi({
				username:decrypt(Storage.getItem('username_key')),
				old_password: dataForm.value.password,
				password:dataForm.value.newPassword
			}).then(() => {
				btnloading.value = false
				ElMessage.success(t('profile.success'))
				visible.value = false
				location.reload()
			}).catch(() => {
				btnloading.value = false
			})
		}else{
			ElMessage.error(t('profile.errorMsg'))
		}
	})
}
const handleDataFormName = () => {
	dataFormNameRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}
		btnloading.value = true
		// 修改用户名
		updateUsernameApi({
			id: store.userStore.user.id,
			name:dataFormName.value.name
		}).then(async () => {
			ElMessage.success(t('successMsg'))
			// // 关闭当前tab
			// closeTab(router, route)
			let login_data = Storage.getItem('login_info')
			login_data.user_info.name = dataFormName.value.name
			Storage.setItem('login_info', login_data)
			await store.userStore.getUserInfoAction()
			btnloading.value = false
			visibleName.value = false
		}).catch(() => {
			btnloading.value = false
			ElMessage.error(t('errorMsg'))
		})
	})
}
</script>
<style lang="scss" scoped>
	.avatar-box{
		position: relative;
		width: 100px;
		height: 100px;
		border-radius: 50%;
		overflow: hidden;
		img{
			width: 100px;
			height: 100px;
			border-radius: 50%;
		}
		.change{
			position: absolute;
			bottom: 4px;
			left: 0;
			width: 100%;
			background-color: rgba($color: #B7E1E9, $alpha: 0.8);
			height: 30px;
			line-height: 30px;
			text-align: center;
			cursor: pointer;
			color: #333;
		}
	}
</style>
